package com.tdam2014.grupo3.tasks;

import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONException;

import android.content.Context;
import android.os.AsyncTask;

import com.tdam2014.grupo3.R;
import com.tdam2014.grupo3.db.CommentDatabaseHelper;
import com.tdam2014.grupo3.db.PhotoDatabaseHelper;
import com.tdam2014.grupo3.entities.Comment;
import com.tdam2014.grupo3.flickr.Flickr;
import com.tdam2014.grupo3.flickr.FlickrException;
import com.tdam2014.grupo3.flickr.interfaces.CommentInterface;
import com.tdam2014.grupo3.flickrviewer.FlickrViewer;
import com.tdam2014.grupo3.interfaces.UpdateableUI;
import com.tdam2014.grupo3.utils.NetworkUtils;

public class UpdateCommentsListTask extends AsyncTask<String, Object, ArrayList<Comment>> {
	
	private Context context;
	private String photoID;
	private UpdateableUI updateableUI;
	private boolean isConnected;
	
	public UpdateCommentsListTask(Context context, String photoID) {
		super();
		this.context = context;
		this.photoID = photoID;
	}

	public UpdateCommentsListTask(Context context, String photoID,
			UpdateableUI updateableUI) {
		super();
		this.context = context;
		this.photoID = photoID;
		this.updateableUI = updateableUI;
	}

	@Override
	protected void onPreExecute() {
		if(updateableUI != null) updateableUI.onStartUpdate();
	}

	@Override
	protected ArrayList<Comment> doInBackground(String... params) {
		isConnected = NetworkUtils.isOnline(context);
		if(!isConnected) {
			try {
				Thread.sleep(300);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return null;
		}
		
		Flickr flickr = new Flickr(FlickrViewer.API_KEY);
		CommentInterface ci = flickr.getCommentInterface();
		
		try {
			return ci.getList(params[0]);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (FlickrException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	@Override
	protected void onPostExecute(ArrayList<Comment> result) {
		if (result != null) {
			if(!result.isEmpty()) {
				CommentDatabaseHelper commentDatabaseHelper = new CommentDatabaseHelper(context);
				commentDatabaseHelper.addComments(result, photoID);
				
				PhotoDatabaseHelper photoDatabaseHelper = new PhotoDatabaseHelper(context);
				int countComments = photoDatabaseHelper.getPhotoCountComments(photoID);
				if(countComments != -1 && countComments != result.size()) {
					photoDatabaseHelper.updatePhotoCountComments(photoID, result.size());
				}
			}
			
			if(updateableUI != null) updateableUI.onFinishUpdate();
		}		
		else if(updateableUI != null) {
			if(isConnected) updateableUI.informError(context.getResources().getString(R.string.error_getting_comments));
			else updateableUI.informError(context.getResources().getString(R.string.not_connected));
		}
	}
}
